package com.ztjava.pay.service;

import com.ztjava.core.base.BaseService;
import com.ztjava.pay.model.PayAccount;
import com.ztjava.pay.model.PayRecord;

public class PayService extends BaseService{
	public double getBalance(Integer user_id){
		PayAccount payAccount = PayAccount.dao.findFirst("select * from "+PayAccount.tablename+" where user_id=?",user_id);
		if(payAccount == null){
			payAccount = new PayAccount();
			payAccount.set("user_id", user_id);
			payAccount.save();
			payAccount = PayAccount.dao.findById(payAccount.getInt("id"));
		}
		return payAccount.getBigDecimal("balance").doubleValue();
	}
	
	public boolean costBalance(Integer user_id,double money,String remark){
		PayAccount payAccount = PayAccount.dao.findFirst("select * from "+PayAccount.tablename+" where user_id=?",user_id);
		if(payAccount == null){
			payAccount = new PayAccount();
			payAccount.set("user_id", user_id);
			payAccount.save();
			payAccount = PayAccount.dao.findById(payAccount.getInt("id"));
		}
		if(payAccount.getBigDecimal("balance").doubleValue()<money){
			return false;
		}
		payAccount.set("balance", payAccount.getBigDecimal("balance").doubleValue()-money).update();
		PayRecord payRecord = new PayRecord();
		payRecord.set("user_id", user_id);
		payRecord.set("money", -money);
		payRecord.set("remark", remark);
		payRecord.save();
		return true;
	}
}
